package com.shaper2.minaapps;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created with IntelliJ IDEA.
 * User: danlek
 * Date: 2012-11-01
 * Time: 09:27
 * To change this template use File | Settings | File Templates.
 */
public class MyLocationListener extends Observable implements LocationListener {
    private Context myContext;
    private MySQLiteDatabaseHandler myDatabaseHandler;
    private List<Observer> observers;

    public MyLocationListener(Context _context, MySQLiteDatabaseHandler databaseHandler){
        myContext = _context;
        myDatabaseHandler = databaseHandler;
        observers = new ArrayList<Observer>();
    }

    @Override
    public void onLocationChanged(Location location) {
        //Log.d("Insert", "Insert new coordinates");
        myDatabaseHandler.addCoordinate(new MyCoordinates((int)(location.getLatitude() * 1E6)
                , (int)(location.getLongitude() * 1E6)));
        notifyObservers();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void onProviderEnabled(String s) {
        Toast.makeText(myContext, "GPS unit is on", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onProviderDisabled(String s) {
        Toast.makeText(myContext, "GPS unit is off", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public int countObservers() {
        return observers.size();
    }

    @Override
    public synchronized void deleteObservers() {
        observers.removeAll(observers);
    }

    @Override
    public void notifyObservers() {
        for(int i = 0; i < countObservers(); i++){
            observers.get(i).update(this, null);
        }
    }
}
